#coding=utf-8
from uliweb import expose

def convert_text(text):
    from uliweb.utils.rst import to_html
    from wikiparser import wikiparse
    
    return wikiparse(to_html(text))
    
@expose('/', defaults={'pagename':'Index'})
@expose('/<pagename>')
def wiki_page(pagename):
    from models import WikiPage, WikiChangeSet

    wiki = WikiPage.get(WikiPage.c.name == pagename)
    if not wiki:
        if pagename == 'Index':
            content = """Welcome to Uliweb wiki
=======================

This app is developed by Limodou.

Hope you enjoy it!
"""
            wiki = WikiPage(name='Index', title='Welcome', content=content).save()
            wiki.new_revision(wiki.content, wiki.title, wiki.format)
    
    if wiki:
        rev = int(request.GET.get('rev', 0))
        rev_time = None
        if rev:
            r = WikiChangeSet.get((WikiChangeSet.c.wiki==wiki.id) & (WikiChangeSet.c.revision==rev))
            rev_time = r.modify_time.strftime('%Y-%m-%d %H:%M:%S')
            content = convert_text(r.old_content)
        else:
            content = convert_text(wiki.content)
        return {'pagename':wiki.name, 'title':wiki.title, 'content':content, 'revision':rev, 'rev_time':rev_time}
    else:
        return redirect(url_for(wiki_edit, pagename=pagename))

@expose('/<pagename>/edit')
def wiki_edit(pagename):
    from models import WikiPage
    from forms import WikiEdit

    wiki = WikiPage.get(WikiPage.c.name == pagename)
    if wiki:
        data = wiki.to_dict()
    else:
        data = {}
    
    form = WikiEdit(data=data)
    if request.method == 'GET':
        return {'pagename':pagename, 'form':form}
    elif request.method == 'POST':
        if form.validate(request.POST):
            if wiki:
                if (wiki.content != form.content.data.rstrip()) or (wiki.title != form.title.data.strip()) :
                    wiki.title = form.title.data.strip()
                    wiki.content = form.content.data.rstrip()
                    wiki.save()
                    wiki.new_revision(wiki.content, wiki.title, wiki.format, request.user)
            else:
                wiki = WikiPage(name=pagename, title=form.title.data.strip(), content=form.content.data.strip()).save()
                wiki.new_revision(wiki.content, wiki.title, wiki.format, request.user)
            return redirect(url_for(wiki_page, pagename=pagename))
        else:
            return {'pagename':pagename, 'form':form}
        
@expose('/<pagename>/delete')
def wiki_delete(pagename):
    from models import WikiPage, WikiChangeSet
    
    wiki = WikiPage.get(WikiPage.c.name == pagename)
    if wiki:
        WikiChangeSet.filter(WikiChangeSet.c.wiki == wiki.id).delete()
        wiki.delete()
        return redirect(url_for(wiki_page))
    else:
        error("There is not %s wikipage, please check first" % pagename)
    
@expose('/<pagename>/revision')
def wiki_revision(pagename):
    from models import WikiPage, WikiChangeSet
    
    wiki = WikiPage.get(WikiPage.c.name == pagename)
    if wiki:
        changeset = wiki.changeset.all().order_by(WikiChangeSet.c.revision.desc())
        return {'wiki':wiki, 'changeset':changeset}
    else:
        error("There is not %s wikipage, please check first" % pagename)
    
@expose('/<pagename>/diff')
def wiki_diff(pagename):
    rev1 = int(request.GET['rev1'])
    rev2 = int(request.GET['rev2'])
    
    from models import WikiPage, WikiChangeSet
    
    wiki_id, wiki_title = WikiPage.filter(WikiPage.c.name == pagename).values_one(WikiPage.c.id, WikiPage.c.title)
    c1 = WikiChangeSet.get((WikiChangeSet.c.wiki == wiki_id) & (WikiChangeSet.c.revision==rev1))
    c2 = WikiChangeSet.get((WikiChangeSet.c.wiki == wiki_id) & (WikiChangeSet.c.revision==rev2))
    
    title = diff(c1.old_title, c2.old_title)
    content = diff(c1.old_content, c2.old_content)
    
    return {'pagename':pagename, 'title':title, 'content':content, 'wiki_title':wiki_title}

def diff(txt1, txt2):
    from diff_match_patch import diff_match_patch
    
    dmp = diff_match_patch()
    
    diffs = dmp.diff_main(txt1, txt2)
    dmp.diff_cleanupEfficiency(diffs)
    return dmp.diff_prettyHtml(diffs)

@expose('/<pagename>/revert')
def wiki_revert(pagename):
    from models import WikiPage, WikiChangeSet

    wiki = WikiPage.get(WikiPage.c.name == pagename)
    rev = int(request.GET['rev'])
    r = WikiChangeSet.get((WikiChangeSet.c.wiki==wiki.id) & (WikiChangeSet.c.revision==rev))
    if (wiki.content != r.old_content) or (wiki.title != r.old_title) :
        wiki.title = r.old_title
        wiki.content = r.old_content
        wiki.save()
        wiki.new_revision(wiki.content, wiki.title, wiki.format, request.user)
    return redirect(url_for(wiki_page, pagename=pagename))
    